package com.automation.ljf.strategy.impl;

import com.jayway.jsonpath.JsonPath;
import com.automation.ljf.domain.dataobject.CaseStepDO;
import com.automation.ljf.strategy.OperationStrategy;
import com.automation.ljf.util.DriverUtils;
import com.automation.ljf.util.ResultMessage;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.stereotype.Component;

/**
 * 输入数据
 *
 * @author lijiefeng
 * @since 2021/8/25
 */
@Slf4j
@Component("INPUT")
public class InputStrategyImpl implements OperationStrategy {

    @Override
    public ResultMessage doOperation(ChromeDriver driver, CaseStepDO caseStepDO, String jsonData) {
        String windowHandle = driver.getWindowHandle();
        String jsonParams = null;
        try{
            boolean res = DriverUtils.isElementExist(driver, By.xpath(caseStepDO.getStepXpath()));
            if (!res){
                return ResultMessage.error().addData("errorMsg", "找不到对应元素").addData("window", windowHandle);
            }
            //解析json字符串，根据jsonpath表达式获取对应的值
             jsonParams = JsonPath.read(jsonData, caseStepDO.getStepJsonpath());
            //进行输入
            WebElement we = driver.findElement(By.xpath(caseStepDO.getStepXpath()));
            if (!we.isEnabled()){
                //元素不可操作/编辑，返回错误
                return ResultMessage.error("测试用例" + caseStepDO.getCaseId() + "的步骤" + caseStepDO.getStepId() + "出现异常")
                        .addData("errorMsg", "元素不可操作/编辑").addData("window", windowHandle);
            }
            //输入
            we.sendKeys(jsonParams);
            Thread.sleep(1500);

        }catch (Exception e){
            return ResultMessage
                    .error("测试用例" + caseStepDO.getCaseId() + "出现异常，用例步骤" + caseStepDO.getStepId() + "出现未知异常")
                    .addData("errorMsg", "未知异常");
        }

        return ResultMessage.ok("输入成功").addData("parameter", jsonParams).addData("window", windowHandle);
    }

}
